﻿using IPR_StudyMeetingMrgSys.Enums;
using IPR_StudyMeetingMrgSys.Extension;
using IPR_StudyMeetingMrgSys.Models;
using log4net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Http.Filters;

namespace IPR_StudyMeetingMrgSys.Filters
{
    public class SecurityFilter : ActionFilterAttribute
    {
        ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            //Login方法不需要进行签名验证
            if (actionContext.ActionDescriptor.ActionName == "Login")
            {
                base.OnActionExecuting(actionContext);
                return;
            }

            ResultMsg resultMsg = null;
            var request = actionContext.Request;
            string signtoken = string.Empty;
            string userid = string.Empty;
            if (request.Headers.Contains("userid"))
            {
                userid = HttpUtility.UrlDecode(request.Headers.GetValues("userid").FirstOrDefault());
            }
            if (request.Headers.Contains("signtoken"))
            {
                signtoken = HttpUtility.UrlDecode(request.Headers.GetValues("signtoken").FirstOrDefault());
            }
            log.Info($"token信息:request-userid={userid};request-signtoken={signtoken}");
            //判断token是否有效
            if (string.IsNullOrEmpty(userid) || HttpRuntime.Cache.Get(userid) == null || HttpRuntime.Cache.Get(userid).ToString() != signtoken)
            {
                log.Info($"token失效");
                resultMsg = new ResultMsg();
                resultMsg.StatusCode = (int)StatusCodeEnum.TokenInvalid;
                resultMsg.Info = StatusCodeEnum.TokenInvalid.GetEnumText();
                resultMsg.Data = "";
                actionContext.Response = HttpResponseExtension.toJson(JsonConvert.SerializeObject(resultMsg));

                base.OnActionExecuting(actionContext);
                return;
            }
            else
            {
                log.Info($"token验证通过");
                LoginUser.EmpID = userid;
                LoginUser.IsSuperAdmin = userid == "admin" ? true : false;
                LoginUser.UserInfo = HttpRuntime.Cache.Get(signtoken) as Model.UserInfo;

                base.OnActionExecuting(actionContext);
            }
        }
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);
        }

    }
}